<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="reportName">
        <el-input v-model="formData.reportName" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType">
        <el-select v-model="formData.dataType" placeholder="请选择数据类型">
          <el-option
            v-for="dict in availableDataTypes"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报表类型" prop="reportType">
        <el-select v-model="formData.reportType" placeholder="请选择报表类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_REPORT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceReportApi, DeviceReportVO } from '@/api/mqtt/devicereport'

/** MQTT报表分类 表单 */
defineOptions({ name: 'DeviceReportForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const existingList = ref<DeviceReportVO[]>([]) // 已存在的列表数据

const formData = ref({
  id: undefined,
  deviceId: undefined as number | undefined,
  reportName: undefined,
  dataType: undefined,
  mqttNum: 1,
  reportType: undefined
})

// 计算可用的数据类型（过滤掉已存在的）
const availableDataTypes = computed(() => {
  const allTypes = getStrDictOptions(DICT_TYPE.MQTT_DEVICE_REPORT_DATA_TYPE)
  return allTypes
})

const formRules = reactive({
  // deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
  reportName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  dataType: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
  mqttNum: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  reportType: [{ required: true, message: '报表类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (
  type: string,
  id?: number,
  existingListData?: DeviceReportVO[],
  deviceId?: number
) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  existingList.value = existingListData || []
  resetForm()
  // 设置设备ID
  formData.value.deviceId = deviceId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceReportApi.getDeviceReport(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log('=== submitForm 开始执行 ===')
  console.log('formType:', formType.value)
  console.log('existingList:', existingList.value)
  console.log('formData:', formData.value)

  // 校验表单
  try {
    await formRef.value.validate()
    console.log('=== 表单验证通过 ===')
  } catch (error) {
    console.log('=== 表单验证失败 ===', error)
    return
  }

  // 检查数据类型是否重复
 

  const isDuplicate = existingList.value.some((item) => {
    if (formType.value === 'create') {
      // 新增时，检查是否有相同的数据类型
      return item.dataType === formData.value.dataType
    } else {
      // 修改时，检查除了当前记录外是否有相同的数据类型
      return item.id !== formData.value.id && item.dataType === formData.value.dataType
    }
  })

  console.log('=== 重复检查结果 ===', isDuplicate)

  if (isDuplicate) {
    message.error('该数据类型已存在！')
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceReportVO
    if (formType.value === 'create') {
      await DeviceReportApi.createDeviceReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceReportApi.updateDeviceReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceId: undefined,
    reportName: undefined,
    dataType: undefined,
    mqttNum: undefined,
    reportType: undefined
  }
  formRef.value?.resetFields()
}
</script>
